import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/config/sqflite/class_db_provider.dart';
import 'package:flutter_douban/main_page/class/model/class_item_model.dart';
import 'package:flutter_douban/main_page/class/view/class_cell_view.dart';
import 'package:flutter_douban/main_page/collect/view/class_item_cell.dart';
import 'package:flutter_douban/tool_views/ios_loading_dialog.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';

class CollectionClassPage extends StatefulWidget {
  const CollectionClassPage({Key? key}) : super(key: key);

  @override
  _CollectionClassPageState createState() => _CollectionClassPageState();
}

class _CollectionClassPageState extends State<CollectionClassPage> {
  /// 列表数据
  List<ClassItemModel> _classList = [];
  StreamSubscription<CacheClassEvent>? _cacheClassSubscription;
  StreamSubscription<LoginEvent>? _loginSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _loginSubscription = EventBusUtil.listen((event) {
      setState(() {
        _getData();
      });
    });
    _cacheClassSubscription = EventBusUtil.listen((event) {
      setState(() {
        _getData();
      });
    });
    _getData();
  }

  Future<void> _getData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? numberId = prefs.getString(AppConfig.numberId);
    if(numberId == null){
      numberId = '123';
    }
    ClassDbProvider provider = new ClassDbProvider();
    List<ClassItemModel> list = [];
    provider.getClassInfo(numberId).then((value) => {
          list = value,
          setState(() {
            _classList = list;
          }),
        });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: AppColors.page,
      padding: EdgeInsets.only(left: 14, right: 14, top: 10),
      child: GridView.builder(
          itemCount: _classList.length,
          primary: false,
          shrinkWrap: true,
          physics: AlwaysScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              //横轴元素个数
              crossAxisCount: 2,
              //纵轴间距
              mainAxisSpacing: 1.0,
              //横轴间距
              crossAxisSpacing: 10.0,
              //子组件宽高长度比例
              childAspectRatio: 0.53),
          itemBuilder: (BuildContext context, int index) {
            return ClassItemCell(
              model: _classList[index],
            );
          }),
    );
  }
}
